package com.transsion.clouddemo.core.ulo.down

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.gms.dynamic.IFragmentWrapper
import com.transsion.cloud_client_sdk.CloudSDKManager
import com.transsion.cloud_upload_sdk.utils.Utils
import com.transsion.clouddemo.CloudApplication
import com.transsion.clouddemo.R
import com.transsion.clouddemo.core.Custom.BaseInfoAdapter
import com.transsion.clouddemo.core.Custom.CloudClickListener
import com.transsion.clouddemo.core.DataGenerator
import com.transsion.clouddemo.core.ulo.upload.UploadFragment.Companion.FAIL
import com.transsion.clouddemo.databinding.CloudDownBinding

class DownFragment :Fragment(), Handler.Callback {

    private lateinit var mBinding : CloudDownBinding
    companion object {

        const val TAG = "zhangxin"
        const val URL_DOWN = 1000
        const val SCENE_DOWN = 1001
        const val POINT_DOWN = 1002
        const val URL_SUCCESS="success"
        const val URL_FAIL="fail"


        fun newInstance(): DownFragment {
            return DownFragment()
        }
    }

    private val urlDownAdapter by lazy { BaseInfoAdapter(urlDownList) }
    private val sceneDownAdapter by lazy { BaseInfoAdapter(sceneDownList) }
    private val pointDownAdapter by lazy { BaseInfoAdapter(pointDownList) }


    private val internalHandler = Handler(Looper.getMainLooper(),this)

    @SuppressLint("NotifyDataSetChanged")
    override fun handleMessage(msg: Message): Boolean {
        Log.d(TAG, "handle massage ${msg.what}")
        when (msg.what) {
            URL_DOWN ->{
                urlDownList.add(DownMessageItem(msg.data.getString(URL_SUCCESS)!!,msg.data.getString(URL_FAIL)))
                urlDownAdapter.notifyDataSetChanged()
                mBinding.urlRecyclerView.scrollToPosition(urlDownList.size - 1)

            }
            SCENE_DOWN ->{
                sceneDownList.add(DownMessageItem(msg.data.getString(URL_SUCCESS)!!,msg.data.getString(URL_FAIL)))
                sceneDownAdapter.notifyDataSetChanged()
                mBinding.sceneRecyclerView.scrollToPosition(sceneDownList.size - 1)

            }
            POINT_DOWN ->{
                pointDownList.add(DownMessageItem(msg.data.getString(URL_SUCCESS)!!,msg.data.getString(URL_FAIL)))
                pointDownAdapter.notifyDataSetChanged()
                mBinding.pointRecyclerView.scrollToPosition(pointDownList.size - 1)

            }
        }
        return true
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        mBinding = CloudDownBinding.inflate(inflater, container, false)

        //初始化页面内容
        initdescription()
        //初始化url的RecyclerView
        initInfoRecyclerView()
        //初始化url列表按钮
        initUrlDown()
        //初始化scene列表按钮
        initSceneDown()
        //初始化断点列表按钮
        initPointDown()



        return mBinding.root

    }

    private  val urlDownList: MutableList<DownMessageItem> by lazy { DataGenerator.urlDown }
    private  val sceneDownList: MutableList<DownMessageItem> by lazy { DataGenerator.sceneDown }
    private  val pointDownList: MutableList<DownMessageItem> by lazy { DataGenerator.pointDown }



    fun initdescription() {
        mBinding.descriptionOne.text=getString(R.string.cloud_down_one_method,Utils.sdkDirectory())
        mBinding.descriptionTwo.text=getString(R.string.cloud_down_two_method,Utils.sdkDirectory())
        mBinding.descriptionThere.text=getString(R.string.cloud_down_there_method,Utils.sdkDirectory())
    }

    private fun initInfoRecyclerView() {

        mBinding.urlRecyclerView.apply {
            layoutManager = LinearLayoutManager(context) // 线性布局管理器
            adapter = urlDownAdapter // 设置适配器
        }

        mBinding.sceneRecyclerView.apply {
            layoutManager = LinearLayoutManager(context) // 线性布局管理器
            adapter = sceneDownAdapter // 设置适配器
        }

        mBinding.pointRecyclerView.apply {
            layoutManager = LinearLayoutManager(context) // 线性布局管理器
            adapter = pointDownAdapter // 设置适配器
        }
    }

    fun initUrlDown() {
        mBinding.buttonDownUrl.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {

                mBinding.urlRecyclerView.visibility = View.VISIBLE
                mBinding.buttonDownUrlDelete.visibility = View.VISIBLE

                Log.e(TAG,"使用url方式开始下载=================")
                mBinding.buttonDownUrl.apply {
                    isEnabled=false
                    text=resources.getString(R.string.cloud_downing)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }


                //下载
                CloudSDKManager.getInstance().download(DataGenerator.downUrlRes) { saveName, logInfo, respose ->
                    Log.e(TAG, "操作保存名称：$saveName")
                    Log.e(TAG,"操作完成后的Loginfo：$logInfo")
                    Log.e(TAG,"操作完成后的回复内容：$respose")

                    val message = internalHandler.obtainMessage(URL_DOWN) // 创建Message对象并设置what字段

                    val bundle = Bundle().apply {
                        putString(URL_SUCCESS, saveName) // 将成功URL放入Bundle
                        putString(FAIL,DataGenerator.codeToReason[logInfo.code])
                    }
                    if (logInfo.success()) {
                        urlDownList[0].fail = ""
                        urlDownList[1].fail = ""
                    }
                    message.data = bundle // 设置Message的data属性
                    if (logInfo.message != "decode error") {//不考虑解码问题，不影响下载结果
                        internalHandler.sendMessage(message)
                    }
                    mBinding.buttonDownUrl.apply {
                        isEnabled=true
                        text=resources.getString(R.string.cloud_down)
                        setTextColor(context.getColor(R.color.cloud_text_default))
                    }
                }

            }

        })

        mBinding.buttonDownUrlDelete.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                if (urlDownList.size > 2) {  // 检查列表是否有超过两项
                    Log.e(TAG,"开始删除数据=================")
                    urlDownList.subList(2, urlDownList.size).clear()
                }
                urlDownList[0].fail = "下载失败!"
                urlDownList[1].fail = "失败原因："
                urlDownAdapter.notifyDataSetChanged()
            }

        })

    }

    fun initSceneDown() {
        mBinding.buttonDownScene.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {

                mBinding.sceneRecyclerView.visibility = View.VISIBLE
                mBinding.buttonDownSceneDelete.visibility = View.VISIBLE

                Log.e(TAG,"使用场景方式开始下载=================")
                mBinding.buttonDownScene.apply {
                    isEnabled=false
                    text=resources.getString(R.string.cloud_downing)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }

                //下载
                CloudSDKManager.getInstance().download(CloudApplication.currentScene) { saveName, logInfo, response ->
                    Log.e(TAG, "操作保存名称：$saveName")
                    Log.e(TAG, "操作完成后的Loginfo：$logInfo")
                    Log.e(TAG, "操作完成后的回复内容：$response")

                    val message = internalHandler.obtainMessage(SCENE_DOWN) // 创建Message对象并设置what字段
                    val bundle = Bundle().apply {
                        putString(URL_SUCCESS, if (saveName.equals(CloudApplication.currentScene)) "已是最新数据" else saveName) // 将成功URL放入Bundle
                        putString(FAIL,DataGenerator.codeToReason[logInfo.code])
                    }

                    if (logInfo.success()) {
                        sceneDownList[0].fail = ""
                        sceneDownList[1].fail = ""
                    }
                    message.data = bundle // 设置Message的data属性
                    if (logInfo.message != "decode error") {//不考虑解码问题，不影响下载结果
                        internalHandler.sendMessage(message)
                    }

                    mBinding.buttonDownScene.apply {
                        isEnabled=true
                        text=resources.getString(R.string.cloud_down)
                        setTextColor(context.getColor(R.color.cloud_text_default))
                    }
                }


            }

        })

        mBinding.buttonDownSceneDelete.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                if (sceneDownList.size > 2) {  // 检查列表是否有超过两项
                    Log.e(TAG,"场景开始删除数据=================")
                    sceneDownList.subList(2, sceneDownList.size).clear()
                }
                sceneDownList[0].fail = "下载失败!"
                sceneDownList[1].fail = "失败原因："
                sceneDownAdapter.notifyDataSetChanged()
            }

        })

    }

    fun initPointDown() {
        mBinding.buttonDownPoint.setOnClickListener(object : CloudClickListener() {
            override fun onSingleClick(view: View) {

                mBinding.pointRecyclerView.visibility = View.VISIBLE
                mBinding.buttonDownPointDelete.visibility = View.VISIBLE

                Log.e(TAG,"开始下载=================")
                mBinding.buttonDownPoint.apply {
                    isEnabled=false
                    text=resources.getString(R.string.cloud_downing)
                    setTextColor(context.getColor(R.color.cloud_text_selected))
                }

                //下载
                CloudSDKManager.getInstance().download(DataGenerator.downUrlRes) { saveName, logInfo, respose ->
                    Log.e(TAG, "操作保存名称：$saveName")
                    Log.e(TAG,"操作完成后的Loginfo：$logInfo")
                    Log.e(TAG,"操作完成后的回复内容：$respose")

                    val message = internalHandler.obtainMessage(POINT_DOWN) // 创建Message对象并设置what字段
                    val bundle = Bundle().apply {
                        putString(URL_SUCCESS, saveName) // 将成功URL放入Bundle
                        putString(FAIL,DataGenerator.codeToReason[logInfo.code])
                    }
                    if (logInfo.success()) {
                        pointDownList[0].fail = ""
                        pointDownList[1].fail = ""
                    }
                    message.data = bundle // 设置Message的data属性
                    internalHandler.sendMessage(message)
                }
                mBinding.buttonDownPoint.apply {
                    isEnabled=true
                    text=resources.getString(R.string.cloud_down)
                    setTextColor(context.getColor(R.color.cloud_text_default))
                }

            }

        })

        mBinding.buttonDownPointDelete.setOnClickListener(object :CloudClickListener(){
            @SuppressLint("NotifyDataSetChanged")
            override fun onSingleClick(view: View) {
                if (pointDownList.size > 2) {  // 检查列表是否有超过两项
                    Log.e(TAG,"开始删除数据=================")
                    pointDownList.subList(2, pointDownList.size).clear()
                }
                pointDownList[0].fail = "下载失败!"
                pointDownList[1].fail = "失败原因："
                pointDownAdapter.notifyDataSetChanged()
            }

        })

    }



    override fun onDestroyView() {
        super.onDestroyView()
    }


}